layui.use(["layer", "echarts"], function () {
  // 2020-03-25 HF sessionStorage中取出数据
  var token = sessionStorage.getItem("newtoken");
  var device = JSON.parse(sessionStorage.getItem("Savedevice")).deviceCode;

  var $ = layui.jquery,
    echarts = layui.echarts;
  $("#Myloading2").remove();
  /*************曲线图初始化*******************/
  var beginTime1 = $("#beginTime").val();
  var endTime1 = $("#endTime").val();

  if (beginTime1 == "" && endTime1 == "") {
    function add0(m) {
      return m < 10 ? "0" + m : m;
    } //避免少0
    // 当前时间
    var time = new Date();
    var year = time.getFullYear();
    var month = time.getMonth() + 1;
    var date = time.getDate();
    var hours = time.getHours();
    var minutes = time.getMinutes();
    var seconds = time.getSeconds();
    var s2 =
      year +
      "-" +
      add0(month) +
      "-" +
      add0(date) +
      " " +
      add0(hours) +
      ":" +
      add0(minutes) +
      ":" +
      add0(seconds);
    // var s2 = setInterval(function(){
    //     return 2
    // })
    // console.log(s2);
    var s1 =
      year +
      "-" +
      add0(month) +
      "-" +
      add0(date) +
      " " +
      add0(0) +
      ":" +
      add0(0) +
      ":" +
      add0(0);
    $("#beginTime").val(s1);
    $("#endTime").val(s2);

    // 实时更新当前时间
    var cltime = setInterval(function () {
      let nowtime = new Date();
      var s1 = GMTToStr(nowtime);
      $("#endTime").val(s1);
    }, 1000);

    // 初始化为当前一天的时间
    beginTime1 = s1;
    endTime1 = s2;
    $.ajax({
      url:
        "/oms-web/cable/trouble-point?token=" +
        token +
        "&beginTime=" +
        beginTime1 +
        "&endTime=" +
        endTime1 +
        "&devCode=" +
        device,
      dataType: "json",
      type: "get",
      contentType: "application/json",
      success: function (data) {
        console.log(data);
        if (data.code === 0) {
          $("#CurveSeach").click();
        }
      },
      error: function () {
        layer.msg("数据请求错误,请检查时间格式！");
        layer.close(index);
      },
      // ****************************************//
    });
  }

  // 获取时间 请求数据
  // ****************************************//
  $("#CurveSeach").click(function () {
    var beginTime = $("#beginTime").val();
    var endTime = $("#endTime").val();

    // 判断时间非空
    if (beginTime != "" && endTime != "") {
      function getDaysByDateString(dateString1, dateString2) {
        var startDate = Date.parse(dateString1);
        var endDate = Date.parse(dateString2);
        var diffDate = endDate - startDate + 1 * 24 * 60 * 60 * 1000; //
        var days = parseInt(diffDate / (1 * 24 * 60 * 60 * 1000));
        return days;
      }
      // 验证查询时间   不能过大和过小
      days = getDaysByDateString(beginTime, endTime);
      if (days > 180) {
        layer.msg("错误！查询时间段不能大于180天");
        return false;
      }
      if (days < 0 || days == 0) {
        layer.msg("错误！开始时间必须小于结束时间");
        return false;
      }
      index = layer.load(1);
      getHcurveData(beginTime, endTime);
    } else {
      layer.msg("请填写开始时间 -- 结束时间！");
    }
  });
  /***********************最近24小时***********************/
  $("#24hours").click(function () {
    var echartsPies = echarts.init(document.getElementById("echarts-scatter"));
    let end = new Date();
    let start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
    var s1 = GMTToStr(start);
    var s2 = GMTToStr(end);
    index = layer.load(1);
    echartsPies.clear();
    getHcurveData(s1, s2);
  });
  /***********************最近三天***********************/
  $("#threeDay").click(function () {
    var echartsPies = echarts.init(document.getElementById("echarts-scatter"));
    let end = new Date();
    let start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
    var s1 = GMTToStr(start);
    var s2 = GMTToStr(end);
    index = layer.load(1);
    echartsPies.clear();
    getHcurveData(s1, s2);
  });
  $("#week").click(function () {
    var echartsPies = echarts.init(document.getElementById("echarts-scatter"));
    let end = new Date();
    let start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
    var s1 = GMTToStr(start);
    var s2 = GMTToStr(end);
    index = layer.load(1);
    echartsPies.clear();
    getHcurveData(s1, s2);
  });
  /***********************最近一个月***********************/
  $("#month").click(function () {
    var echartsPies = echarts.init(document.getElementById("echarts-scatter"));
    let end = new Date();
    let start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
    var s1 = GMTToStr(start);
    var s2 = GMTToStr(end);
    index = layer.load(1);
    echartsPies.clear();
    getHcurveData(s1, s2);
  });
  /**********************************************/

  /**********************************************/
  //2020-03-27 HF  请求曲线接口
  function getHcurveData(beginTime, endTime) {
    var echartsPies = echarts.init(document.getElementById("echarts-scatter"));
    $.ajax({
      url:
        "/oms-web/cable/trouble-point?token=" +
        token +
        "&beginTime=" +
        beginTime +
        "&endTime=" +
        endTime +
        "&devCode=" +
        device,
      dataType: "json",
      type: "get",
      contentType: "application/json",
      success: function (value) {
        // console.log(value, "123", "value");
        if (value.code === 0) {
          // loading加载动画
          layer.close(index);
          // console.log(data.data);
          var DataTable = value.data;
          if (DataTable != null && DataTable != undefined) {
            let xTitle = [];
            let days = [];
            let hours = [];
            let datas = [];

            DataTable.map((i) => {
              if (i.type === "A") {
                i["num"] = 0;
              }
              if (i.type === "B") {
                i["num"] = 1;
              }
              if (i.type === "C") {
                i["num"] = 2;
              }
              hours.push(i.value);
              days.push(i.type);
              xTitle.push(i.value);
              console.log(xTitle, "xtitle");
              let newList = Array.from(new Set(days));
              newList.sort();
              datas.push([i.num, i.datetime, i.value]);
              // console.log(datas, "111");

              const title = [];
              const singleAxis = [];
              const series = [];
              newList.forEach(function (day, idx) {
                title.push({
                  textBaseline: "middle",
                  top: ((idx + 0.5) * 100) / 7 + "%",
                  text: day,
                });
                singleAxis.push({
                  left: 150,
                  type: "category",
                  boundaryGap: false,
                  data: xTitle,
                  top: (idx * 100) / 7 + 5 + "%",
                  height: 100 / 7 - 10 + "%",
                  axisLabel: {
                    interval: 2,
                  },
                });
                series.push({
                  singleAxisIndex: idx,
                  coordinateSystem: "singleAxis",
                  type: "scatter",
                  data: [],
                });
              });
              datas.forEach(function (dataItem) {
                series[dataItem[0]]?.data.push([dataItem[1], dataItem[2]]);
              });

              option = {
                tooltip: {
                  position: "top",
                },
                title: title,
                singleAxis: singleAxis,
                series: series,
              };

              console.log(echartsPies.clear);
              echartsPies.clear();
              echartsPies.setOption(option);
              // echartsPies.setOption(option);
            });
          }
        }
      },
      error: function () {
        layer.msg("数据请求错误,请检查时间格式！");
        layer.close(index);
      },
      // ****************************************//
    });
  }

  //获取时间函数
  function GMTToStr(time) {
    function add0(m) {
      return m < 10 ? "0" + m : m;
    } //避免少0
    var time = new Date(time);
    var year = time.getFullYear();
    var month = time.getMonth() + 1;
    var date = time.getDate();
    var hours = time.getHours();
    var minutes = time.getMinutes();
    var seconds = time.getSeconds();
    return (
      year +
      "-" +
      add0(month) +
      "-" +
      add0(date) +
      " " +
      add0(hours) +
      ":" +
      add0(minutes) +
      ":" +
      add0(seconds)
    );
  }

  $("#beginTime").datetimepicker({
    language: "zh-CN", //显示中文
    format: "yyyy-mm-dd hh:ii:ss", //显示格式
    // minView: "month",//设置只显示到月份
    initialDate: new Date(), //初始化当前日期
    autoclose: true, //选中自动关闭
    todayBtn: true, //显示今日按钮
    // minView:'month',
    language: "zh-CN",
  });
  $("#endTime")
    .datetimepicker({
      language: "zh-CN", //显示中文
      format: "yyyy-mm-dd hh:ii:ss", //显示格式
      // minView: "month",//设置只显示到月份
      initialDate: new Date(), //初始化当前日期
      autoclose: true, //选中自动关闭
      todayBtn: true, //显示今日按钮
      // minView:'month',
      language: "zh-CN",
    })
    .on("changeDate", function (ev) {
      window.clearInterval(cltime);
    });
});
